<?php

class CiucourseCiustudentsController extends AppController {

    var $name = 'CiucourseCiustudents';
    var $components = array('Session');
	
    function index() {
        $this->CiucourseCiustudent->recursive = 0;
        $controller = 'CiucourseCiustudent';
        $conditions = array();
		$id = 0;
        if (!empty($this->data)) {
            $document = $this->data[$controller]['document'];
            $raw = $this->CiucourseCiustudent->Ciuuser->findByDocument($document);
            $id = $raw['Ciuuser']['id'];
            if (empty($id)) {
                $this->Session->setFlash(__('No se encontraron datos para el estudiante', true));
                $this->redirect(array('action' => 'index'));
            }
			$conditions[ $controller . ".ciuuser_id" ] = $id;	
		}
		//$conditions[]= "CiucourseCiustudent.ciucurspersstate_id <> 3" ;
		$currentPeriod = $this->getCurrentPeriod();
		$conditions[]= "Ciucourse.ciuacademicperiod_id = $currentPeriod" ;
		$this->paginate[$controller]['conditions'] = $conditions;
        $this->set('ciucourseCiustudents', $this->paginate());
    }
	
    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid ciucourse ciustudent', true));
            $this->redirect(array('action' => 'index'));
        }
		$ciucourseCiustudent  = $this->CiucourseCiustudent->read(null, $id);
		$this->set('ciucourse', $this->CiucourseCiustudent->Ciucourse->read(null, $ciucourseCiustudent['Ciucourse']['id']));
        $this->set('ciucourseCiustudent', $ciucourseCiustudent);
    }

    function add() {
        if (!empty($this->data)) {
            $this->CiucourseCiustudent->create();
            if ($this->CiucourseCiustudent->save($this->data)) {
                $this->Session->setFlash(__('The ciucourse ciustudent has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The ciucourse ciustudent could not be saved. Please, try again.', true));
            }
        }
        $ciucourses = $this->CiucourseCiustudent->Ciucourse->find('list');
        $ciuusers = $this->CiucourseCiustudent->Ciuuser->find('list');
        $this->set(compact('ciucourses', 'ciuusers'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid ciucourse ciustudent', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->CiucourseCiustudent->save($this->data)) {
                $this->Session->setFlash(__('The ciucourse ciustudent has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The ciucourse ciustudent could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->CiucourseCiustudent->read(null, $id);
        }
        $ciucourses = $this->CiucourseCiustudent->Ciucourse->find('list');
        $ciuusers = $this->CiucourseCiustudent->Ciuuser->find('list');
        $ciustudenttypes = $this->CiucourseCiustudent->Ciustudenttype->find('list');
        $ciucurspersstates = $this->CiucourseCiustudent->Ciucurspersstate->find('list');
        $this->set(compact('ciucourses', 'ciuusers', 'ciustudenttypes', 'ciucurspersstates'));
    }

    function matriculate($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid ciucourse ciustudent', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $esDuplicado = $this->CiucourseCiustudent->isDuplicated($this->data['CiucourseCiustudent']);
            if ($esDuplicado) {
                $this->Session->setFlash(__('Consignación ya se encuentra registrada, verifique los datos', true));
            } else {
                $record = $this->data;
				$record["CiucourseCiustudent"]["ciucurspersstate_id"] = 3;
				$ciuuser_id=$record["CiucourseCiustudent"]["ciuuser_id"];
				
				$ciusubject_id=$this->data['CiucourseCiustudent']['ciusubject_id'];
				
				
                if ($this->CiucourseCiustudent->save($record)) {
					$this->setmatriculated($ciuuser_id, $ciusubject_id);
				    $this->Session->setFlash(__('The ciucourse ciustudent has been saved', true));
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The ciucourse ciustudent could not be saved. Please, try again.', true));
                    $this->redirect(array('action' => 'matriculate',$id));
                }
            }
        }
		$ciuuser_id=0;
        if (empty($this->data)) {
            $this->data = $this->CiucourseCiustudent->read(null, $id);
			$ciuuser_id = $this->data['CiucourseCiustudent']['ciuuser_id'];
        }
        $ciucourses = $this->CiucourseCiustudent->Ciucourse->find('list');
        $ciuusers = $this->CiucourseCiustudent->Ciuuser->find('list' , array('conditions'=>array('Ciuuser.id'=>$ciuuser_id) ));
        $ciustudenttypes = $this->CiucourseCiustudent->Ciustudenttype->find('list', array('conditions'=>array('Ciustudenttype.id !='=>6) ));
        $ciucurspersstates = $this->CiucourseCiustudent->Ciucurspersstate->find('list');
        $this->set(compact('ciucourses', 'ciuusers', 'ciustudenttypes', 'ciucurspersstates'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for ciucourse ciustudent', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->CiucourseCiustudent->delete($id)) {
            $this->Session->setFlash(__('Ciucourse ciustudent deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Ciucourse ciustudent was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

	//lista los cursos que ha tomado un estudiante
	// null: usuario actual
	// 0: todos
	// n: el usuario indicado.
    function history($ciuuser_id = null) {
        $this->CiucourseCiustudent->recursive = 2;
		$conditions=array();
		if($ciuuser_id != null){
			if($ciuuser_id>0){
				$conditions[] = "CiucourseCiustudent.ciuuser_id = $ciuuser_id" ;
			}
		}else{
			$ciuuser_id = $this->getConnectedUser();
			$conditions[] = "CiucourseCiustudent.ciuuser_id = $ciuuser_id" ;
		}
		$conditions[]=array('CiucourseCiustudent.ciucurspersstate_id' => array(4, 5 ));
		$this->paginate['CiucourseCiustudent']['conditions'] = $conditions;
		$this->set('ciucourseCiustudents', $this->paginate());
    }

    function changelevel($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid ciucourse ciustudent', true));
            $this->redirect(array('action' => 'indexmodificar'));
        }
        if (!empty($this->data)) {
            if ($this->CiucourseCiustudent->save($this->data)) {
                $this->Session->setFlash(__('The ciucourse ciustudent has been saved', true));
                $this->redirect(array('action' => 'indexmodificar'));
            } else {
                $this->Session->setFlash(__('The ciucourse ciustudent could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->CiucourseCiustudent->read(null, $id);
        }
        $cursoactual = $this->data['Ciucourse'];
        $estadoactual = $this->data['CiucourseCiustudent']['ciucurspersstate_id'];
        $cursosDisponibles = $this->CiucourseCiustudent->Ciucourse->find('all', array(
            'fields' => array('Ciucourse.id', 'concat(Ciucourse.id," - ",Ciusubject.name," - ",Ciuroom.name," - ",Ciuuser.first_names," - ",Ciutimetable.name) as name'),
            'conditions' => array('Ciuacademicperiod.isactive' => 1)
                )
        );
        $opciones = array();
        foreach ($cursosDisponibles as $key => $val) {
            $coursid = $val['Ciucourse']['id'];
            $coursname = $val[0]['name'];
            $opciones[$coursid] = $coursname;
        }
        $ciuusers = $this->CiucourseCiustudent->Ciuuser->find('list');
        $ciustudenttypes = $this->CiucourseCiustudent->Ciustudenttype->find('list', array('conditions'=>array('Ciustudenttype.id !='=>6) ));
        $ciucurspersstates = $this->CiucourseCiustudent->Ciucurspersstate->find('list');
        $this->set(compact('opciones', 'ciucourses', 'ciuusers', 'ciustudenttypes', 'ciucurspersstates', 'cursoactual'));
    }

    function indexmodificar() {
        $this->CiucourseCiustudent->recursive = 0;
        $controller = 'CiucourseCiustudent';
        $conditions = array();
        $id = 0;
        if (!empty($this->data)) {

            $document = $this->data[$controller]['document'];
            $raw = $this->CiucourseCiustudent->Ciuuser->findByDocument($document);
            $id = $raw['Ciuuser']['id'];
            if (empty($id)) {
                //      $this->Session->setFlash(__('No se encontraron datos para el estudiante', true));
                $this->redirect(array('action' => 'indexmodificar'));
            }
            $conditions[$controller . ".ciuuser_id"] = $id;
            $this->paginate[$controller]['conditions'] = $conditions;
        }
        $this->set('ciucourseCiustudents', $this->paginate());
    }

    function coreregister() {
        $this->CiucourseCiustudent->recursive = 2;
        $controller = 'CiucourseCiustudent';
        $conditions = array();
        App::import('Component', 'Session');
        $mySession = new SessionComponent();
        $userInfo = $mySession->read('Auth.Ciuuser');
        $id = $userInfo['id'];
        if (!$id) {
            $this->Session->setFlash(__('Invalid ciuuser', true));
            $this->redirect(array('action' => 'home'));
        }
        
        //se verifica que este en el rango de fechas para ingresar las calificaciones
        $sqlFecha = "select DATE(score_registration_start) start,"
                         . "DATE(score_registration_end) end "
                  . "from ciuacademicperiods "
                  . "where isactive=1 ";
        $fechaPara = $this->CiucourseCiustudent->query($sqlFecha);
        $startDate = $fechaPara['0']['0']['start'];
        $endDate   = $fechaPara['0']['0']['end'];
        
        $sqlcurso = "select concat(subject.name,' - ', room.name,' - ',timetable.name) as name,
                            ciucourse_ciustudent.ciucourse_id, 
                            count(ciucourse_ciustudent.ciuuser_id) totalStudents
                       from ciucourse_ciustudents ciucourse_ciustudent
                          join ciucourses ciucourse         on (ciucourse_ciustudent.ciucourse_id = ciucourse.id)
                           join ciuacademicperiods  periodo on (periodo.id = ciucourse.ciuacademicperiod_id)
                            join     ciusubjects  subject   on (ciucourse.ciusubject_id=subject.id)
                            join     ciurooms     room      on (ciucourse.ciuroom_id=room.id)
                            join     ciutimetables  timetable on (ciucourse.ciutimetable_id=timetable.id)
                      where ciucourse_ciustudent.ciucurspersstate_id in (3,4,5)
                        and periodo.isactive=1
                        and ciucourse.ciuuser_id=".$id."
                   group by ciucourse_ciustudent.ciucourse_id, concat(subject.name,' - ', room.name,' - ',timetable.name)
                   having count(ciucourse_ciustudent.ciuuser_id) > 0";
        // 
        $listcurso = $this->CiucourseCiustudent->query($sqlcurso);
        $opciones = array();
        foreach ($listcurso as $key => $val) {
            $nameCourse = $val[0]['name'];
            $idCourse = $val['ciucourse_ciustudent']['ciucourse_id'];
            $opciones[$idCourse] = $nameCourse;
        }
        $conditions[$controller . ".ciucourse_id"] = $this->data['Ciucourse Ciustudents']['Curso'];
        $conditions[$controller . ".ciucurspersstate_id"] = array(3,4,5);
        $this->paginate[$controller]['conditions'] = $conditions;
        $this->set('ciucourseCiustudents', $this->paginate());
        $this->set(compact('opciones'));
        $this->set('startDate',$startDate);
        $this->set('endDate',$endDate);
    }
    function score($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid ciucourse ciustudent', true));
            $this->redirect(array('action' => 'coreregister'));
        }
        $sqlaprobar= "select definition from ciuparameters where name='NOTA_MIN_APROBATORIA'";
        $notaaprobatoria=$this->CiucourseCiustudent->query($sqlaprobar);
        
        if (!empty($this->data)) {
            if ($this->CiucourseCiustudent->save($this->data)) {
                $this->Session->setFlash(__('The ciucourse ciustudent has been saved', true));
                $this->redirect(array('action' => 'coreregister'));
            } 
            else {
                $this->Session->setFlash(__('Los datos ingresados presentan errores y no se almacenaron, por favor intente de nuevo.', true));
                $this->redirect(array('action' => 'score',$id));       
            }
        }
        if (empty($this->data)) {
            $this->data = $this->CiucourseCiustudent->read(null, $id);
        }
        $ciuusers = $this->CiucourseCiustudent->Ciuuser->find('list');
        $ciucurspersstates = $this->CiucourseCiustudent->Ciucurspersstate->find('list');
        $this->set('notaaprobatoria',$notaaprobatoria['0']['ciuparameters']['definition']);
        $this->set(compact('ciuusers', 'ciucurspersstates'));
    }
	
	function isMatriculated($ciuuser_id=null){
		$result=false;
		if( $ciuuser_id != null ){
			if ($this->CiucourseCiustudent->hasAny(array(
		 'CiucourseCiustudent.ciuuser_id' => $ciuuser_id,
		 'CiucourseCiustudent.ciucurspersstate_id' => 3 ))) {
				$result=true;
			}
		}
		return $result;
	}
	
	function setMatriculated($ciuuser_id=null, $ciusubject_id=null){
		if($ciuuser_id != null){
			$userData=array();
			$userData['Ciuuser']['id']=$ciuuser_id;
			$userData['Ciuuser']['ciustudentstate_id']=3; //matriculado
			$userData['Ciuuser']['ciuuserstate_id']=1;    //activo
			$this->CiucourseCiustudent->Ciuuser->save( $userData );
			
			$userInfo=$this->CiucourseCiustudent->Ciuuser->findById($ciuuser_id);
			$ciuplan_id=$userInfo['Ciuuser']['ciuplan_id'];
			
			//$subjectInfo=$this->CiucourseCiustudent->Ciuuser->findById($ciusubject_id);
			//$ciuplan_id=$subjectInfo['Ciuuser']['ciuplan_id'];
			
			
			
			
			
			if ($this->CiucourseCiustudent->Ciuuser->CiuplanCiuuser->hasAny(array(
		 'CiuplanCiuuser.ciuuser_id' => $ciuuser_id,
		 'CiuplanCiuuser.ciuplan_id' => $ciuplan_id ))) {
				$this->updateStudentPlan( $ciuuser_id, $ciuplan_id, $ciusubject_id);
			}else{
				$this->createStudentPlan( $ciuuser_id, $ciuplan_id, $ciusubject_id);
			}
			$userplanData=array();
			$userplanData['CiuplanCiuuser']['ciuuser_id']=$ciuuser_id;
			$userplanData['CiuplanCiuuser']['ciuplan_id']=$ciuplan_id;
			$this->CiucourseCiustudent->Ciuuser->Ciuplan->save( $userData );
			
		}
	}
		
	function createStudentPlan($ciuuser_id, $ciuplan_id, $ciusubject_id){
		$record=array();
		$record['CiuplanCiuuser']['ciuplan_id']   = $ciuplan_id;
		$record['CiuplanCiuuser']['last_subject'] = $ciusubject_id;
		$record['CiuplanCiuuser']['ciuuser_id']   = $ciuuser_id;
		$this->CiucourseCiustudent->Ciuuser->CiuplanCiuuser->save($record);
	}
	
	function updateStudentPlan($ciuuser_id, $ciuplan_id, $ciusubject_id){
		$sql="update ciuplan_ciuusers set last_subject=$ciusubject_id where ciuuser_id=$ciuuser_id  and ciuplan_id=$ciuplan_id";
		$this->CiucourseCiustudent->query($sql);
	}	
		
	function getConnectedUserData(){
		App::import('Component', 'Session');
		$mySession = new SessionComponent();
		$userInfo = $mySession->read('Auth.Ciuuser');
		$username=$userInfo['username'];
		return $this->CiucourseCiustudent->Ciuuser->findByUsername($username);
	}

	function getConnectedUser(){
		$ciuuserData = $this->getConnectedUserData();
		return $ciuuserData['Ciuuser']['id'];
	}
	
	function getCurrentPeriod(){
		$periodData =$this->CiucourseCiustudent->Ciucourse->Ciuacademicperiod->findByIsactive(1);
		return $periodData['Ciuacademicperiod']['id'];
	}
	
    function listcurrent(){
        $this->Ciucourses->recursive = 1;
        $controller='CiucourseCiustudents';
        $ciuuser_id    = $this->CiucourseCiustudent->Ciuuser->getConnectedUser();
        $conditions=array();
        $conditions[]=array('CiucourseCiustudent.ciuuser_id' => $ciuuser_id);
        $conditions[]=array( "Ciucourse.ciuacademicperiod_id" => $this->getCurrentPeriod() );
        $this->paginate[$controller]['conditions'] = $conditions;
        $this->set('ciucourses', $this->paginate());
	}
}
